<template>
  <div v-drag class="search-event-card" v-if="isShow">
    <el-card style="width: auto; max-height: 500px" shadow="hover">
      <div class="btns">
        <el-radio-group v-model="type" @mousedown.stop @change="handleChange">
          <el-radio-button label="事件信息" value="eventInfo"></el-radio-button>
          <el-radio-button label="统计图" value="taotalPic"></el-radio-button>
          <el-radio-button label="热力图" value="hotPic"></el-radio-button>
        </el-radio-group>
        <el-button type="primary" style="margin-right: 40px" @mousedown.stop @click="exportToExcel">导出Excel</el-button>
      </div>
      <el-table
        v-if="type === 'eventInfo'"
        :data="currentTableData"
        stripe
        style="width: 100%; user-select: none; margin-top: 15px"
        fit
        border
        height="300"
        :header-cell-style="{
          background: '#F5F7FA',
          color: '#909399',
          height: '60px',
        }"
      >
        <el-table-column align="center" prop="AttValue[0]" label="事件编号" width="180" />
        <el-table-column align="center" prop="AttValue[1]" label="事件类型" width="180" />
        <el-table-column align="center" prop="AttValue[2]" label="事件等级" width="180" />
        <el-table-column sortable align="center" prop="AttValue[3]" label="发生时间" width="180" />
        <el-table-column align="center" prop="AttValue[4]" label="发生地点" width="180" />
        <el-table-column align="center" prop="AttValue[5]" label="车牌号" width="180" />
        <el-table-column align="center" prop="AttValue[6]" label="驾驶员" width="180" />
        <el-table-column align="center" prop="AttValue[7]" label="处理状态" width="180" />
      </el-table>
      <div v-if="type === 'taotalPic'" class="total-picture">
        <el-card style="max-width: 480px" class="total-picture-item">
          <div class="chart-wrapper">
            <v-chart :option="typeOption" :autoresize="true" />
          </div>
        </el-card>
        <el-card style="max-width: 480px" class="total-picture-item">
          <div class="chart-wrapper">
            <v-chart :option="levelOption" :autoresize="true" />
          </div>
        </el-card>
      </div>
      <div v-if="type === 'hotPic'" class="hot-picture">
        <div class="switch"><span>设置热点图:</span><el-switch v-model="switchValue" @mousedown.stop @change="handleSwitch" /></div>
        <div class="radius">
          <span style="margin-right: 20px">热点半径(radius size):</span>
          <el-slider @mousedown.stop style="width: 150px" v-model="radius" :min="1" :max="40" @input="handleRadius" />
        </div>
        <div class="blur">
          <span style="margin-right: 20px">模糊尺寸(blur size):</span>
          <el-slider @mousedown.stop style="width: 150px" v-model="blur" :min="1" :max="40" @input="handleBlur" />
        </div>
      </div>
      <el-pagination
        v-if="type === 'eventInfo'"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2, 5, 10, 20]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
        @mousedown.stop
      />
    </el-card>
    <div class="close" @mousedown.stop @click="isShow = false">
      <span>X</span>
    </div>
  </div>
</template>

// SearchEventCard.vue
<script setup>
import { onMounted, watch, nextTick, onUnmounted, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useMap } from '@/stores/useMap.js';
import {
  currentPage,
  pageSize,
  total,
  isShow,
  type,
  currentTableData,
  handleCurrentChange,
  handleSizeChange,
  exportToExcel,
  initDraw,
  handleChange,
  handleMapClick,
  cleanup,
  eventList,
  heatMapFeatures,
} from '@/hooks/eventInfoHook.js';

import { renderChart } from '@/hooks/totalPicture.js';
// import { setRadius, setBlur } from '@/hooks/heatMapHook.js';

// 获取store
const { map, draw } = storeToRefs(useMap());
const { setDraw } = useMap();
const typePieOption = ref(null);
const legendData = ref([]);
const seriesData = ref([]);
const switchValue = ref(false);
// 控制滑块
const radius = ref(10);
const blur = ref(10);
const heatMapFeaturesVal = ref([]);
const eventListVal = ref([]);

let heatmapSource = null;
let heatmapLayer = null;

const heatMap = (map, showHeatmap, radius, blur, features, eventListVal) => {
  if (showHeatmap) {
    if (!heatmapSource) {
      queryEventSuccess(map, radius, blur, features, eventListVal);
    }
  } else {
    heatmapSource.clear();
    heatmapSource = null;
  }
};

// 成功回调
const queryEventSuccess = (map, radius, blur, features, eventListVal) => {
  console.log(222, features);
  for (var i = 0; i < features.length; i++) {
    features[i].set('weight', parseFloat(eventListVal[i].AttValue[2]) * 0.2);
  }
  if (!heatmapSource) {
    heatmapSource = new ol.source.Vector({
      wrapX: false,
    });
  }
  // 创建热力图对象
  heatmapLayer = new ol.layer.Heatmap({
    source: heatmapSource,
    radius: radius, //半径大小
    blur: blur, //模糊大小
  });

  map.addLayer(heatmapLayer);

  heatmapSource.addFeatures(features);
};

const handleSwitch = showHeatmap => {
  heatMap(map.value, showHeatmap, radius.value, blur.value, heatMapFeaturesVal.value, eventListVal.value);
  // console.log(e, radius.value, blur.value, map.value);
};

const handleRadius = () => {
  setRadius(radius.value);
};
const handleBlur = () => {
  setBlur(blur.value);
};

const setRadius = value => {
  heatmapLayer.setRadius(value);
};

const setBlur = value => {
  heatmapLayer.setBlur(value);
};

watch(heatMapFeatures, newValue => {
  if (newValue && newValue.length > 0) {
    // console.log(999, newValue);
    heatMapFeaturesVal.value = newValue;
  }
});

watch(
  eventList,
  newValue => {
    if (newValue && newValue.length > 0) {
      // 统计事件类型
      let typeCount = {};
      let levelCount = {};
      eventListVal.value = newValue;
      newValue.forEach(item => {
        // console.log(111, item);
        if (item.AttValue[1]) {
          typeCount[item.AttValue[1]] = (typeCount[item.AttValue[1]] || 0) + 1;
        }
        if (item.AttValue[2]) {
          if (item.AttValue[2] == 1) {
            levelCount['重大事故'] = (levelCount['重大事故'] || 0) + 1;
          } else if (item.AttValue[2] == 2) {
            levelCount['特大事故'] = (levelCount['特大事故'] || 0) + 1;
          } else if (item.AttValue[2] == 3) {
            levelCount['一般事故'] = (levelCount['一般事故'] || 0) + 1;
          } else {
            levelCount['轻微事故'] = (levelCount['轻微事故'] || 0) + 1;
          }
        }
      });

      // 更新事件类型图表数据
      typeOption.value.series[0].data = Object.keys(typeCount).map(key => ({
        value: typeCount[key],
        name: `${key} | ${typeCount[key]}`,
      }));

      // 更新事件等级图表数据
      levelOption.value.series[0].data = Object.keys(levelCount).map(key => ({
        value: levelCount[key],
        name: `${key} | ${levelCount[key]}`,
      }));
    }
  },
  { deep: true }
);

onMounted(async () => {
  await nextTick();
  if (map.value) {
    initDraw(map.value, draw.value, setDraw);
  }
});

onUnmounted(() => {
  cleanup(map.value, draw.value);
  heatmapSource.clear();
});

const typeOption = ref({
  title: {
    text: '事件类型分析',
  },
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 20,
  },
  series: [
    {
      name: '事件类型',
      type: 'pie',
      radius: '50%',
      data: [], // 数据将动态更新
      label: {
        show: true,
        position: 'outside',
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
});

const levelOption = ref({
  title: {
    text: '事件等级分析',
  },
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 20,
  },
  series: [
    {
      name: '事件等级',
      type: 'pie',
      radius: '50%',
      data: [], // 数据将动态更新
      label: {
        show: true,
        position: 'outside',
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
});
</script>

<style lang="scss" scoped>
.search-event-card {
  position: absolute;
  width: 900px;
  z-index: 99;
  top: 10%;
  left: 50%;
  transform: translateX(-50%);

  .close {
    position: absolute;
    top: 5px;
    right: 10px;
    font-size: 15px;
    cursor: pointer;
  }

  .btns {
    display: flex;
    gap: 10px;
    justify-content: space-between;
    margin-bottom: 15px;

    .el-radio-group {
      button {
        padding: 10px 25px;
        border: 0.5px solid #ccc;
        background-color: white;
        border-radius: 5px;
        cursor: pointer;
      }
    }
  }

  .total-picture {
    display: flex;
    width: 100%;
    height: 300px;
    gap: 10px;
    .total-picture-item {
      width: 50%;
      height: 300px;
      box-shadow: none;
      border: none;
      border: 1px solid #ccc;
      border-radius: 10px;

      .chart-wrapper {
        width: 100%;
        height: 100%;
        min-height: 300px; // 确保最小高度
      }

      :deep(.echarts) {
        width: 100% !important;
        height: 100% !important;
        min-height: 300px; // 确保最小高度
      }
    }
  }

  .hot-picture {
    width: 100%;
    height: 240px;
    line-height: 80px;
    font-weight: 600;
    .switch {
      height: 80px;
      span {
        margin-right: 20px;
      }
    }
    .radius {
      display: flex;
      width: 100%;
      justify-content: left;
      align-items: center;
    }
    .blur {
      display: flex;
      width: 100%;
      justify-content: left;
      align-items: center;
    }
  }

  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: center;
  }
}

.active {
  background-color: #409eff !important;
  color: #fff;
}
</style>
